package com.eliaukjq.apitoolinterface.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author : eliaukjq
 * Description :
 * @Create : 2023/9/22 - 10:54
 */
@RestController
@RequestMapping("/avatars")
public class RandImages {
    @GetMapping("/sjbz")
    public String randImages(HttpServletRequest request) throws Exception {
        //https://restapi.amap.com/v3/weather/weatherInfo?
        String avatarUrl = "https://api.btstu.cn/sjbz/api.php/";
//        HashMap<String, Object> paramMap = new HashMap<>();
//        paramMap.put("type", "json");
//        paramMap.put("tx", "b1");
//        paramMap.put("key", "2yta7ZzxPfP6YqZZLzQi413D3B");
//        HttpRequest get = HttpUtil.createGet(avatarUrl, true);
        String redirectUrl = getRedirectUrl(avatarUrl);
        return redirectUrl;
//        String url = "http://api.btstu.cn/sjbz/api.php/";
//        String body = URLUtil.decode(request.getHeader("body"), CharsetUtil.CHARSET_UTF_8);
//        HttpResponse httpResponse = HttpRequest.get(url + "?" + body)
//                .execute();
//        return httpResponse.body();
    }

    /**
     * 获取重定向地址
     *
     * @param path
     * @return
     * @throws Exception
     */
    private String getRedirectUrl(String path) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(path)
                .openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(5000);
        String location = conn.getHeaderField("Location");
        return location;
    }
}
